/**
 *  Eclipse Public License 1.0
 */
package org.fireblade.easysms;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

/**
 * Simple tcp/ip server for wifi and usb connections
 */
public class Wifi_USBServer implements Runnable {

  /**
   * own log tag
   */
  private static final String LOGTAG = MainActivity.EASY_SMS + Wifi_USBServer.class.getSimpleName();

  boolean shouldStop = false;
  boolean hasStopped = false;
  Service serviceInstance;


  /*
   * (non-Javadoc)
   * @see java.lang.Runnable#run()
   */
  public void run() {
    try {
      SharedPreferences pref = serviceInstance.getSharedPreferences(MainActivity.EASY_SMS_SP,
        Context.MODE_PRIVATE);
      int port = pref.getInt(MainActivity.PORT, 2511);
      ServerSocket tcpServerSocket = new ServerSocket(port);
      Log.i(LOGTAG, "STARTED!");
      Socket tcpClientSocket = null;
      while (true) {
        Log.d(LOGTAG, "Warte auf connect");
        try {
          tcpClientSocket = tcpServerSocket.accept();
        } catch (SocketTimeoutException e) {
          if (shouldStop) {
            Log.d(LOGTAG, "Stop requested...");
            break;
          }
          continue;
        }
        Log.d(LOGTAG, "Connect!");
        BufferedInputStream bufferedIn = new BufferedInputStream(tcpClientSocket.getInputStream(), 256);
        BufferedOutputStream bufferedOut = new BufferedOutputStream(tcpClientSocket.getOutputStream(), 4096);
        HttpActionHandler.handleClient(bufferedIn, bufferedOut, serviceInstance);
        try {
          bufferedIn.close();
          bufferedOut.flush();
          bufferedOut.close();
          tcpClientSocket.close();
        } catch (SocketException e) {
          Log.e(LOGTAG, "Something wrong with our client :(", e);
        }
        if (shouldStop) {
          Log.d(LOGTAG, "Stop server");
          break;
        }
      }
      tcpServerSocket.close();
      hasStopped = true;
      Log.i(LOGTAG, "STOPPED!");
    } catch (Throwable e) {
      Log.e(LOGTAG, "Server error", e);
    } finally {
      hasStopped = true;
    }
  }
}